<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class GoodsController extends Controller
{
    //显示添加商品页面
    public function getAdd()
    {  
        // lists() 连表查询 单一字段的所有值
        // pluck() 连表查询 单一字段的单一值
        $res = CateController::getCateInfo();
        // dd($res);
        return view('admin.goods.add',['res'=>$res]);
    }

    // 添加商品
    public function postInsert(Request $request)
    {
        // 表单验证
        $this->validate($request, [
            'title' => 'required',
            'price'=>'required',
            'kucun'=>'required',
            'path'=>'required',
            'cate_id'=>'required',

        ],[
            'title.required'=>'请填写商品名称',
            'price.required'=>'请填写价格',
            'kucun.required'=>'请填写库存',
            'path.required'=>'请上传图像',
            'cate_id.required'=>'请备注详情',

        ]);
        // 读取分类信息  去掉多余信息
        $data = $request->except('_token','path');
        // dd($data);
        // 拼接颜色跟尺码
        $data['color'] = implode('@@', $data['color']);
        $data['size'] = implode('@@', $data['size']);
       // dd($data);
        // 把数据插入到主表中
        $gid = DB::table('shop_goods')->insertGetId($data);
        
        // 处理图像
        if($request->hasfile('path')){
            $d = [];
            // 获取所有的文件对象
            $files=$request->file('path');
            foreach ($files as $k => $v) {
                $fileName = time().rand(100000,999999);
                $suffix = $v->getClientOriginalExtension();
                $fileName = $fileName.'.'.$suffix;
                $dir = './Uploads/'.date('Ymd').'/';
                $v->move($dir,$fileName);
                // 拼接OK的图片路径（绝对路径）
                $tmp['path'] = trim($dir.$fileName,'.');
                $tmp['goods_id'] = $gid;

                $d[] = $tmp;
            }
            
            // 将图片信息插入到附加表中放进来
            DB::table('shop_goopics')->insert($d);
        }
        if($gid){
            return redirect('/admin/goods/manage')->with('info','添加商品成功');
        }else{
            return back()->with('info','添加失败');
        }
    }

    // 商品列表
    public function getManage(Request $request)
    {
        // 分页获取商品信息
         $goods = DB::table('shop_goods')
                ->leftJoin('shop_cates','shop_goods.cate_id','=','shop_cates.id')
                ->select('shop_cates.name as cate_name','shop_goods.*')
                ->where(function($query) use ($request){
                    $k = $request->input('keyword');
                    if(!empty($k)){
                        $query->where('title','like','%'.$k.'%');
                     } 
                 })->paginate($request->input('num',5));
         // dd($goods);
        // 解析模板 分配变量
        return view('admin.goods.index', ['goods' => $goods,'request'=>$request]);
    }

    // 商品的修改
    public function getEdit(Request $request)
    {
        // 获取用户的id
        $id = $request->input('id');
        // 获取id的信息
        $goods = DB::table('shop_goods')->where('id',$id)->first();
        // dd($goods);
        $cates = CateController::getCateInfo();

        //  拆分尺码 
         $color = explode('@@',$goods->color);
         $size  = explode('@@',$goods->size);
         $goods->color = $color;
         $goods->size = $size;
        // 获取图片
         $path = DB::table('shop_goods')
         ->join('shop_goopics','shop_goopics.goods_id','=',"shop_goods.id")
         ->where('shop_goods.id',$id)->get();
         // dd($path);
         // dd($goods);
        // 解析模板 分配变量
       return view('admin.goods.edit',['goods'=>$goods,'cates'=>$cates,'path'=>$path]);
    }


    // 商品的更新
    public function postUpdate(Request $request)
    {
        // dd($request->all());

        $data = $request->except('_token','id');
        $color = implode($data['color'],'@@');
        $size = implode($data['size'],'@@');
        $data['color'] = $color;
        $data['size'] = $size;

        //更新数据库信息
        $res = DB::table('shop_goods')->where('id',$request->input('id'))->update($data);
        if($res){
            return redirect('/admin/goods/manage')->with('info','修改成功');
        }else{
            return back()->with('info','修改失败，请重新填写');
        }
    }

    // 商品的删除
    public function getDelete(Request $request)
    {
        $id =  $request->input('id');
        $res = DB::table('shop_goods')->where('id',$id)->delete();
        if($res)
        {
            return redirect('/admin/goods/manage')->with('info','删除成功');
        }else{
            return back()->with('info','删除失败');
        }
    }

    // 商品的详情
    public function getDetail(Request $request)
    {
        $id = $request->input('id');
        // dd($id);
        $res = DB::table('shop_goods')->where('id',$id)->first();
        // 拆分颜色和尺码
        $color = explode('@@',$res->color);
        $size = explode('@@',$res->size);
        $res->color = $color;
        $res->size = $size;
        // dd($res);
        // 获取分类标题
         $cates = CateController::getCateInfo();
         // dd($cates);
         // 获取图像 goods->id = goopics->goods_id
         
         $path = DB::table('shop_goods')
         ->join('shop_goopics','shop_goopics.goods_id','=',"shop_goods.id")
         ->where('shop_goods.id',$id)->get();

    
        return view('admin.goods.detail',['res'=>$res,'cates'=>$cates,'path'=>$path,'request'=>$request]);
    }


    /*====================  前台  ===============================*/

    public function detail(Request $request,$id)
    {    
        // 根据id读取商品的详细信息
        if($id < 148 ){
            $goods = DB::table('shop_goods')->where('id',$id)->first();
            $goods->color = explode('@@',$goods->color);
            $goods->size = explode('@@',$goods->size);
            $images = DB::table('shop_goopics')->where('goods_id',$id)->get();

        }else{
            $goods = DB::table('shop_active')->where('id',$id)->first();
            $goods->color = explode('@@',$goods->color);
            $goods->size = explode('@@',$goods->size);
            $images = DB::table('shop_activepics')->where('aid',$id)->get();
        }

        // 店主推荐
        $tuijian = DB::table('shop_active')->whereIn('id',array(192,200,203))->get();
        foreach($tuijian as $k=>$v){
            $path = DB::table('shop_activepics')->where('id',$v->id)->select('path')->first();
            $tuijian[$k]->path = $path->path;

        }
        // dd($tuijian);
        // 读取当前id的图片信息
        // return view('home.goods.detail',['goods'=>$goods,'images'=>$images,'tuijian'=>$tuijian]); 

      
        // dd($images);
        $comments = DB::table('shop_comments')->where('goods_id',$request->input('goods_id'))->orderBy('id','desc')->paginate(20);

        $data = [];
        foreach($comments as $k=>$v){
            //获取图片
            $path = DB::table('shop_compics')->where('comments_id',$v->id)->get();
            $comments[$k]->pic = $path;
            //获取颜色,尺寸
            $goodsInfo = DB::table('shop_ordgoods')->where('goods_id',$v->goods_id)->where('order_id',$v->order_id)->select('goods_color','goods_size')->first();
            $comments[$k]->goodsInfo = $goodsInfo;
            //获取用户名
            $username = DB::table('shop_users')->where('id',$v->user_id)->select('username')->first();
            $comments[$k]->username = $username;
        }
        // dd($comments);

          $arr=[];
           //把随即的商品放到 一个数组中 作为推荐商品
            for($i=0;$i<5;$i++){
               $number = rand(1,120);  
               $goods = DB::table('shop_goods')->where('id',$number)->first();
               $arr[] = $goods;

            }
               
               //获取商品的图片
               foreach($arr as $k => $v){          
                   $path = DB::table('shop_goopics')->where('goods_id',$v->id)->select('path')->first();
                   $arr[$k]->path = $path->path;                
                 }  

        return view('home.goods.detail',['goods'=>$goods,'images'=>$images,'comments'=>$comments,'tuijian'=>$tuijian,'arr'=>$arr]); 
    }
    
    /**
     * 前台商品列表
     */
    public function getIndex(Request $request)
    {
        $id = $request->id;
        if($id){
            $data = DB::table('shop_goods')
                ->select('id','title','price')
                ->where('cate_id',$id)
                ->paginate(9);

                foreach($data as $k=>$v)
                {
                    $path = DB::table('shop_goopics')->where('goods_id',$v->id)->select('path')->first();
                    $data[$k]->path = $path->path;
                }

        }else{
                $data = DB::table('shop_goods')
                ->select('id','title','price')
                ->paginate(9);

                foreach($data as $k=>$v)
                {
                    $path = DB::table('shop_goopics')->where('goods_id',$v->id)->select('path')->first();
                    $data[$k]->path = $path->path;
                }

        }
         $arr=[];
           //把随即的商品放到 一个数组中 作为推荐商品
            for($i=0;$i<5;$i++){
               $number = rand(1,120);  
               $goods = DB::table('shop_goods')->where('id',$number)->first();
               $arr[] = $goods;

            }
               
               //获取商品的图片
               foreach($arr as $k => $v){          
                   $path = DB::table('shop_goopics')->where('goods_id',$v->id)->select('path')->first();
                   $arr[$k]->path = $path->path;                
                 }  
        return view('home.goods.index',['data'=>$data,'arr'=>$arr]);
    }


    public function postIndex(Request $request)
    {
        $res = $request->input('search');
        $data = DB::table('shop_goods')->where('title','like','%'.$res.'%')->paginate();
        foreach($data as $k=>$v){
            $path = DB::table('shop_goopics')->where('goods_id',$v->id)->select('path')->first();
            $data[$k]->path = $path->path;
        }

        return view('home.goods.index',['data'=>$data]);

    }
}

   

